package com.yangyouli.unity_demo_server.service.impl;

import java.util.regex.Pattern;

import com.yangyouli.unity_demo_server.annotation.Inject;
import com.yangyouli.unity_demo_server.annotation.Injectable;
import com.yangyouli.unity_demo_server.dao.ExpContrastDao;
import com.yangyouli.unity_demo_server.dao.UserDao;
import com.yangyouli.unity_demo_server.dao.UserDataDao;
import com.yangyouli.unity_demo_server.entity.User;
import com.yangyouli.unity_demo_server.entity.UserData;
import com.yangyouli.unity_demo_server.service.UserService;

@Injectable("userService")
public class UserServiceImpl implements UserService {
	@Inject("userDao")
	private UserDao userDao;
	@Inject("userDataDao")
	private UserDataDao userDataDao;
	@Inject
	private ExpContrastDao expContrastDao;
	
	@Override
	public User verifyUser(String account, String password) {
		User user = userDao.findByAccount(account);
		if (user == null) return null;
		if (password.equals(user.getPassword())) {
			return user;
		}
		return null;
	}

	@Override
	public int registerUser(String account, String password) {
		if (userDao.findByAccount(account) != null) return 0;
		// 数字或字母 6到16位
		String isNumOrLetterBetween6And16 = "^[0-9A-Za-z]{6,16}$";
		
		// 账号不规范
		if (!Pattern.matches(isNumOrLetterBetween6And16, account)) return 3;
		// 密码不规范
		if (!checkPwd(password)) return 4;
		User user = new User(0, account, password, "代号无名");
		userDao.insert(user);
		user = userDao.findByAccount(account);
		UserData userData = new UserData(0, user.getId(), "1_1", 0, 1, 0);
		return userDataDao.insert(userData);
	}

	@Override
	public int UpdateExcludeEmail (User user) {
		return userDao.update(user);
	}
	
	@Override
	public int UpdateEmail (User user) {
		return userDao.updateEmail(user);
	}

	@Override
	public boolean changePassowrd(int userId, String newPassword, String oldPassword) {
		User user = userDao.findById(userId);
		if (user.getPassword().equals(oldPassword)) {
			user.setPassword(newPassword);
			return userDao.update(user) == 1;
		}
		return false;
	}
	
	public boolean checkPwd (String password) {
		// 数字、字母或英文半角符号
		String isSigleByteBetween6And16 = "^([A-Z]|[a-z]|[0-9]|[-=;,./~!@#$%^*()_+}{:?]|[|]){6,16}$";
		return Pattern.matches(isSigleByteBetween6And16, password);
	}

	@Override
	public boolean checkNickname(String Nickname) {
		return Nickname.length() >= 2 && Nickname.length() <= 10;
	}

	@Override
	public User findById(int userId) {
		return userDao.findById(userId);
	}

	@Override
	public User findByAccount(String account) {
		return userDao.findByAccount(account);
	}
}
